#!/usr / bin / python
# -*- coding: utf-8 -*-
#%%
from tkinter import *
import socket
import sys
import threading
import tkinter.messagebox as messagebox
import time


class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        frame_left = Frame(self, width=300, height=250)
        frame_left.grid(row=0, column=0)

        frame_right = Frame(self, width=300, height=250)
        frame_right.grid(row=0, column=1)

        button1 = Button(self, text='启动服务', command=self.start_server)
        button1.grid(row=0, column=0, pady=15, ipady=8, ipadx=10)
        button2 = Button(self, text='退出', command=self.quit)
        button2.grid(row=0, column=1, pady=15, ipady=8, ipadx=20)

    def start_server(self):
        HOST = socket.gethostbyname(socket.gethostname())
        print(HOST)
        PORT = 8888  # Arbitrary non-privileged port
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(20)
        messagebox.showinfo('Socket created', 'Socket成功绑定本地ip地址')
        th = threading.Thread(target=server, args=(s,))
        th.setDaemon(True)
        th.start()


def server(s):
    userlist = []
    # Symbolic name meaning all available interfaces

    # Function for handling connections. This will be used to create threads

    def chat(conn, name):
        # infinite loop so that function do not terminate and thread do not
        # end.
        for user in userlist:
            user.send((time.strftime("%Y-%m-%d %H:%M:%S",
                                     time.localtime()) + '\n').encode('utf-8'))
            user.send(('Welcome %s to the room!' % name).encode('utf-8'))
        try:
            while True:
                data = conn.recv(1024).decode('utf-8')
                if not data:
                    break
                elif data == 'quit':  # 用户退出
                    userlist.remove(conn)
                    for user in userlist:
                        user.send((time.strftime("%Y-%m-%d %H:%M:%S",
                            time.localtime()) + '\n').encode('utf-8'))
                        user.send(('%s leaves the room!' %
                                   name).encode('utf-8'))
                    print('%s logout' % name)
                    conn.close()
                    break
                else:
                    for user in userlist:
                        user.send(('%s:' % name + time.strftime("%Y-%m-%d %H:%M:%S",
                                time.localtime()) + '\n').encode('utf-8'))
                        user.send(data.encode('utf-8'))
        except:
            conn.close()

    try:
        while True:
            # wait to accept a connection - blocking call
            conn, addr = s.accept()
            name = conn.recv(1024).decode('utf-8')
            userlist.append(conn)
            print(name)
            # conn.send(data.encode())
            tr = threading.Thread(target=chat, args=(conn, name))
            tr.setDaemon(True)
            tr.start()
    except:
        s.close()

    s.close()


app = Application()

app.master.title('Server')
app.mainloop()
